package com.example.supernote.ui.note.utils

import android.content.ContentResolver
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Base64
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.example.supernote.R
import com.example.supernote.data.network.config.OcrItems
import com.example.supernote.data.network.config.ResultData
import java.io.ByteArrayOutputStream
import java.io.InputStream
import kotlin.math.roundToInt

/**
 * 将 Uri 图片转为 Base64 编码
 *
 * @param uri 图片的Uri路径
 * @param resolver 上下文管理器
 *
 * @return Base64encode
 */
fun getBase64(uri: Uri, resolver: ContentResolver): String {
    // Uri -> InputStream -> bitmap -> byteArray -> Base64
    var result = ""
    val inputStream: InputStream = resolver.openInputStream(uri)!!
    val bitmap = BitmapFactory.decodeStream(inputStream)
    if (bitmap == null || bitmap.isRecycled) {
        return result
    }
    // 将Bitmap转换为字节数组
    val byteArrayOutputStream = ByteArrayOutputStream()
    bitmap.compress(Bitmap.CompressFormat.JPEG, 1, byteArrayOutputStream)
    val byteArray = byteArrayOutputStream.toByteArray()
    // Base64编码
    result = Base64.encodeToString(byteArray, Base64.DEFAULT)
    // 释放资源
    inputStream.close()
    byteArrayOutputStream.close()
    if (!bitmap.isRecycled) {
        bitmap.recycle()
    }

    return result
}

/**
 * 通过 Uri 获取文件名称
 *
 * @param context 上下文对象
 * @param uri 文件Uri
 *
 * @return Uri文件的文件名称
 */
fun getFileAppendnameByUri(context: Context, uri: Uri): String {
    var fileName: String? = null
    if ("file".equals(uri.scheme, true)) {
        fileName = uri.lastPathSegment
    } else {
        val cursor = context.contentResolver.query(uri, null, null, null, null)
        cursor?.use {
            if (it.moveToFirst()) {
                val columnIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (columnIndex != -1) {
                    fileName = it.getString(columnIndex)
                }
            }
        }
    }
    fileName?.let {
        if (fileName!!.contains(".")) {
            return fileName!!.split(".").last()
        }
    }
    return "error"
}

/**
 * OCR工具函数，处理ai识别结果
 */
fun changeToText(wordInfos: List<OcrItems>, angle: Int, endLine: String): String {
    if (wordInfos.isEmpty()) return "error"
    // 0 -- top_left.y 小 -> 大
    // 90 -- top_left.x 大 -> 小
    // 180 -- top_left.y 大 -> 小
    // 270 -- top_left.x 小 -> 大
    wordInfos.forEach {
        it.location.top_left.x = (it.location.top_left.x * 30).roundToInt().toDouble()
        it.location.top_left.y = (it.location.top_left.y * 30).roundToInt().toDouble()
        it.location.top_right.x = (it.location.top_right.x * 30).roundToInt().toDouble()
        it.location.top_right.y = (it.location.top_right.y * 30).roundToInt().toDouble()
    }

    val wordSortedInfos: List<OcrItems> = when (angle) {
        0 -> wordInfos.sortedWith(compareBy<OcrItems> { it.location.top_left.y }.thenBy { it.location.top_left.x })
        90 -> wordInfos.sortedWith(compareBy<OcrItems> { -it.location.top_left.x }.thenBy { it.location.top_left.y })
        180 -> wordInfos.sortedWith(compareBy<OcrItems> { -it.location.top_left.y }.thenBy { -it.location.top_left.x })
        270 -> wordInfos.sortedWith(compareBy<OcrItems> { it.location.top_left.x }.thenBy { -it.location.top_left.y })
        else -> wordInfos
    }

    var page: String = wordSortedInfos[0].words
    var lastX = wordSortedInfos[0].location.top_left.x
    var lastY = wordSortedInfos[0].location.top_right.x
    for (index in 1..<wordSortedInfos.size) {
        val it = wordSortedInfos[index]
        val curX = it.location.top_left.x
        val curY = it.location.top_left.y
        if ((angle == 0 || angle == 180) && curY == lastY) {
            page += "  "
        } else if ((angle == 90 || angle == 270) && curX == lastX) {
            page += "  "
        } else {
            page += endLine
            lastX = curX
            lastY = curY
        }
        page += it.words
    }

    return page
}

/**
 * 语音转文字工具函数，处理ai识别结果
 */
fun dealResultAudioResponse(resultData: List<ResultData>): String {
    var audioText = ""
    resultData.forEach {
        audioText = "$audioText${it.onebest}\n"
    }
    audioText = audioText.trim()
    return audioText.ifEmpty { "未检测到有效文本！" }
}

/**
 * 统一错误提示信息
 */
private val errorMsg = listOf(
    "Network Error",
    "网络错误，请重试",
    "ocr fail",
    "no parameter image"
)

@Composable
fun getFinalTemplate(curText: String): String =
    if (errorMsg.contains(curText)) stringResource(R.string.note_ai_errormsg)
    else if (curText == "error") stringResource(R.string.note_text_warning)
    else if (curText == "Format Error") stringResource(R.string.note_audio_format_error)
    else curText

@Composable
fun isErrorMsg(curText: String): Boolean =
    listOf(
        stringResource(R.string.note_text_warning),
        stringResource(R.string.note_ai_errormsg),
        stringResource(R.string.note_audio_format_error)
    ).contains(curText)